<template>
  <div class="design-query-box">
    <je-form
      :model="formState"
      style="width: 95%; margin: 10px auto"
      autocomplete="off"
      :label-col="{ style: 'width:100px;' }"
      :colon="false"
    >
      <je-row>
        <je-col :span="12">
          <je-form-item label="资源表名" name="tableName" v-bind="validateInfos.tableName">
            <je-grid-select
              v-model:value="formState.tableName"
              name="tableName"
              :select-options="{ title: '选择资源表' }"
              config-info="JE_CORE_RESOURCETABLE,tableName~tableCode~tableId,RESOURCETABLE_TABLENAME~RESOURCETABLE_TABLECODE~JE_CORE_RESOURCETABLE_ID,S"
              :querys="getTableJQuery()"
              @select="handleSeleteTable"
              @reset="handleResetTable"
            />
          </je-form-item>
        </je-col>
        <je-col :span="12">
          <je-form-item label="资源表编码" name="tableCode">
            <je-input v-model:value="formState.tableCode" :disabled="true" />
          </je-form-item>
        </je-col>
      </je-row>
      <je-form-item label="查询条件">
        <je-text-area v-model:value="formState.queryFn" :rows="2" />
        <div class="explain-font" @click="handleJoinSql">SQL拼装器</div>
      </je-form-item>
      <je-form-item label="自定义条件">
        <je-button @click="handleShowEditor">
          <i
            class="fas fa-bolt"
            :style="{
              color: formState.jsScript && formState.jsScript != defaultEditor ? '#F4CE4A' : '',
            }"
          ></i
          ><span>编辑动态查询条件，用于覆盖查询条件</span>
        </je-button>
      </je-form-item>
      <je-form-item>
        <template #label>
          <div class="custom-order-by">
            <i class="fas fa-question-circle" @click="handleCustomOrder" />
            <span>排序条件</span>
          </div>
        </template>

        <je-input v-model:value="formState.orderBy" placeholder="order by ..." />
      </je-form-item>
      <je-form-item label="取前">
        <div class="query-config-options">
          <div class="query-size">
            <je-input-number v-model:value="formState.totalSize" :min="1" />
          </div>
          <div class="query-describe">条数据</div>
        </div>
      </je-form-item>
      <je-form-item label="取前">
        <div class="query-config-options">
          <div class="query-front-size query-front-left">
            <je-input-number v-model:value="formState.frontSize" :min="1" />
          </div>
          <div class="query-front-unit">
            <je-select v-model:value="formState.frontUnit" :options="timeOptions" />
          </div>
          <div class="query-describe">数据</div>
          <div class="query-laber">基准表:</div>
          <div class="query-field-type">
            <je-select
              v-model:value="formState.baseFieldTableCode"
              :options="baseTableOptions"
              @change="changeBaseTable"
            />
          </div>
          <div class="query-laber">基准字段:</div>
          <div class="query-field">
            <je-grid-select
              v-model:value="formState.baseField"
              name="baseField"
              :select-options="{ title: '选择基准字段' }"
              :disabled="!formState.baseFieldTableCode"
              config-info="JE_CORE_TABLECOLUMN,baseField,TABLECOLUMN_CODE,S"
              :querys="getJQuery(formState, 'baseFieldTableCode')"
              :orders="[
                { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
                { code: 'SY_ORDERINDEX', type: 'ASC' },
              ]"
            />
          </div>
          <div class="query-laber">字段类型:</div>
          <div class="query-field-type">
            <je-select v-model:value="formState.fieldType" :options="dateOptions" />
          </div>
        </div>
      </je-form-item>
    </je-form>

    <je-modal
      v-model:visible="visibleEditor"
      title="自定义条件"
      :resize="false"
      :button-align="'center'"
      class="custom-modal"
      cancel-text="关闭"
      @close="handleCancelEditor"
    >
      <template #default>
        <div class="query-editor-box">
          <je-editor-code
            ref="editor"
            v-model:value="formState.jsScript"
            v-model:language="language"
            height="100%"
            width="100%"
            @save="onSave"
            @init="onInit"
            @change="onChange"
          />
        </div>
      </template>
      <template #buttons="modal">
        <je-button type="primary" @click="handleConfirmEditor(modal)">保存</je-button>
        <je-button @click="handleCloseEditor(modal)">关闭</je-button>
      </template>
    </je-modal>
  </div>
</template>

<script>
  import { defineComponent, reactive, toRefs, ref, onMounted, watch } from 'vue';
  import {
    Form,
    Input,
    Button,
    Select,
    Modal,
    EditorCode,
    InputNumber,
    InputSelect,
  } from '@jecloud/ui';
  import { SOURCE_VIEW_QUERY_TIME, SOURCE_VIEW_QUERY_DATE } from '@/helper/constant';
  import { showFuncQuerys } from '@jecloud/func';
  import { useSourceStore } from '@/store/source-store';
  import { Row, Col } from 'ant-design-vue';
  import VueEvent from '@/helper/event';
  import { SOURCE_START_RECOVER } from '@/helper/constant';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'SourceTableConfig',
    components: {
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeInputNumber: InputNumber,
      JeTextArea: Input.TextArea,
      JeButton: Button,
      JeSelect: Select,
      JeModal: Modal,
      JeEditorCode: EditorCode,
      JeGridSelect: InputSelect.Grid,
      JeRow: Row,
      JeCol: Col,
    },
    props: {
      saveStatus: {
        type: Boolean,
        default: () => false,
      },
    },
    emits: ['saveAction'],
    setup(props, { emit }) {
      const sourceStore = useSourceStore(); //数据源全局状态
      const editor = ref(); //代码编辑器
      const curSourceTableCode = sourceStore.getSourceCode();
      const curSourceTableData = sourceStore.getSourceDataByCode(curSourceTableCode);
      const state = reactive({
        curTabSourceCode: sourceStore.getSourceCode(),
        timeOptions: SOURCE_VIEW_QUERY_TIME, //时间选取单位
        dateOptions: SOURCE_VIEW_QUERY_DATE, //字段类型单位
        formState: {
          tableName: '', //资源表名
          tableCode: '', //资源表编码
          tableId: '', //资源表id
          queryFn: '', //SQL拼装器(自定义条件-查询条件) F4CE4A
          editorFn: '', //自定义条件(手动编码编辑)
          jsScript: '', //自定义执行
          orderBy: '', //排序条件
          totalSize: '', //取前多少条数据，默认空字符串为所有
          frontSize: '', //取前...单位...数据的条数
          frontUnit: 'day', //取前...单位...数据的单位
          baseFieldTableCode: '', //基准表
          baseField: '', //基准字段，默认：SYS_CREATETIME
          fieldType: 'date', //字段类型 日期|日期时间|日期月份, 默认：日期
        },
        visibleEditor: false, //自定义条件编辑弹窗
        language: 'javascript', //编辑语言
        defaultEditor: `/**
  * 返回数据格式:
  * return {
  *   params:[{name:'参数1'},{name:'参数2'}],
  *   querys:[{code:'',value:'',type:'',cn:''}]
  * }
  */`,
        temEditorVal: '', //零时保存自定义条件
        baseTableOptions: [], //基准表选项
        rulesRef: {
          tableName: [
            {
              required: true,
              message: '该输入项为必填项',
            },
          ],
        },
        saveAction: false, //保存动作
        temTableName: '', //临时资源表名称
      });
      const { validate, validateInfos, resetFields } = useForm(state.formState, state.rulesRef, {
        onValidate: (...args) => {},
      });
      const methods = {
        handleShowEditor() {
          //打开编辑sql弹窗
          methods.initQueryData();
          state.temEditorVal = state.formState.jsScript;
          state.visibleEditor = true;
        },
        handleCancelEditor({ $modal }) {
          //关闭编辑动态SQL弹窗
          $modal.close();
          state.formState.jsScript = state.temEditorVal;
        },
        handleCloseEditor(modal) {
          modal.close();
        },
        handleConfirmEditor(modal) {
          //确认动态sql编写
          modal.close();
          state.temEditorVal = state.formState.jsScript;
        },
        contrastSql() {
          //对比自定义sql值是否有变化
          state.visibleEditor = true;
          Modal.dialog({
            content: '内容有变动，是否需要保存关闭',
            buttons: [
              {
                text: '保存关闭',
                type: 'primary',
                closable: false,
                handler: ({ button, $modal }) => {
                  button.loading = true;
                  setTimeout(() => {
                    button.loading = false;
                    state.temEditorVal = state.formState.jsScript;
                    state.visibleEditor = false;
                    $modal.close();
                  }, 1000);
                },
              },
              {
                text: '关闭',
                closable: false,
                handler: ({ button, $modal }) => {
                  button.disabled = true;
                  setTimeout(() => {
                    button.disabled = false;
                    $modal.close();
                    state.formState.jsScript = state.temEditorVal;
                    state.visibleEditor = false;
                  }, 1000);
                },
              },
              {
                text: '取消',
              },
            ],
          });
          return false;
        },
        onInit($editor) {
          // console.log('初始化：', $editor, editor.value.getEditor());
        },
        onSave(value) {
          //保存 Ctrl + S
          // console.log('保存成功：', value);
        },
        onChange(value, evt) {
          //数据变动
        },
        setQueryData(queryData) {
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          curSourceData.DATASOURCE_CONFIG = JSON.stringify(queryData);
        },
        //初始化查询配置
        initQueryData() {
          const curSourceData = sourceStore.getSourceDataByCode(curSourceTableCode);
          if (curSourceData.DATASOURCE_CONFIG) {
            state.formState = { ...JSON.parse(curSourceData.DATASOURCE_CONFIG) };
          }
          state.formState.jsScript = state.formState.jsScript || state.defaultEditor;
          state.temTableName = state.formState.tableName;
        },
        //复原查询配置
        recoverQueryData(sourceCode) {
          if (state.curTabSourceCode == sourceCode) {
            const curRecoverSourceData = sourceStore.getSourceDataByCode(sourceCode);
            if (curRecoverSourceData.DATASOURCE_CONFIG) {
              state.formState = { ...JSON.parse(curRecoverSourceData.DATASOURCE_CONFIG) };
              resetFields();
            } else {
              resetFields();
            }
            state.formState.jsScript = state.formState.jsScript || state.defaultEditor;
          }
        },
        //Sql拼装器
        handleJoinSql() {
          showFuncQuerys({
            tableId: state.formState.tableId, // 表Id
            configInfo: 'JE_CORE_TABLECOLUMN,code,TABLECOLUMN_CODE,S',
            querys: [
              { code: 'TABLECOLUMN_TABLECODE', type: '=', value: state.formState.tableCode },
            ],
            value: state.formState.queryFn ? state.formState.queryFn : '',
            callback: (value) => {
              if (value) {
                state.formState.queryFn = value;
              }
            },
          });
        },
        getTableJQuery() {
          //分装资源表j_table_query
          const j_table_query = [
            {
              code: 'SY_PRODUCT_ID',
              type: '=',
              value: curSourceTableData.SY_PRODUCT_ID,
              cn: 'and',
            },
          ];
          return j_table_query;
        },
        //分装j_query
        getJQuery(row, tableCode) {
          const j_query = [
            { code: 'TABLECOLUMN_TABLECODE', type: '=', value: row[tableCode], cn: 'and' },
            { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
          ];
          return j_query;
        },
        //基准表发生变化
        changeBaseTable() {
          //若没有基准表，基准字段为空
          // if (!state.formState.baseFieldTableCode) {
          //   state.formState.baseField = '';
          // }
          state.formState.baseField = '';
        },
        //查看排序条件说明
        handleCustomOrder() {
          Modal.alert('排序条件用于查询的数据排序，您可以根据实际业务场景调整排序列。', 'info');
        },
        //保存验证必填字段
        saveSourceTable() {
          if (state.formState.tableName) {
            state.saveAction = true;
            emit('saveAction', state.saveAction);
            setTimeout(() => {
              state.saveAction = false;
              emit('saveAction', state.saveAction);
            }, 1000);
          } else {
            validate().then(() => {
              state.saveAction = true;
              emit('saveAction', state.saveAction);
              setTimeout(() => {
                state.saveAction = false;
                emit('saveAction', state.saveAction);
              }, 1000);
            });
          }
        },
        //选择资源表
        handleSeleteTable(e) {
          const selectTable = e.rows[0];
          if (selectTable.RESOURCETABLE_TABLENAME != state.temTableName) {
            state.formState.baseFieldTableCode = ''; //基准表
            state.formState.baseField = ''; //基准字段
            resetFields();
          }
        },
        //重置资源表
        handleResetTable() {
          state.formState.baseFieldTableCode = ''; //基准表
          state.formState.baseField = ''; //基准字段
        },
      };
      //监听查询配置发生变化
      watch(
        () => state.formState,
        (newVal, oldVal) => {
          methods.setQueryData(newVal);
        },
        { deep: true },
      );
      //监听资源表的变化
      watch(
        () => state.formState.tableName,
        (val) => {
          state.baseTableOptions = [];
          if (val) {
            let optionItem = {
              label: state.formState.tableName,
              value: state.formState.tableCode,
            };
            state.baseTableOptions.push(optionItem);
            state.temTableName = val;
          }
        },
      );
      //监听保存状态变化
      watch(
        () => props.saveStatus,
        (val) => {
          if (val) {
            methods.saveSourceTable();
          }
        },
      );
      onMounted(() => {
        methods.initQueryData();
        VueEvent.on(SOURCE_START_RECOVER, methods.recoverQueryData);
      });
      return {
        editor,
        validate,
        validateInfos,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .design-query-box {
    width: 100%;
    height: 800px;
    min-width: 1050px;
    overflow: auto;
    padding-top: 10px;
  }
  .explain-font {
    color: #3265f5;
    cursor: pointer;
  }

  .query-editor-box {
    width: 100%;
    height: 100%;
  }
  .query-config-options {
    width: 100%;
    display: flex;
    align-items: center;
    .query-size {
      width: 9%;
      .ant-input-number {
        width: 100%;
      }
    }
    .query-describe {
      padding-left: 5px;
      line-height: 32px;
    }
    .query-laber {
      line-height: 32px;
      margin-left: 25px;
    }
    .query-front-size {
      width: 9%;
      margin: 0 7px;
      .ant-input-number {
        width: 100%;
      }
    }
    .query-front-left {
      margin-left: 0;
    }
    .query-front-unit {
      width: 9%;
    }
    .query-field {
      width: 18%;
      margin-left: 7px;
    }
    .query-field-type {
      margin-left: 7px;
      width: 13%;
    }
  }
  .custom-order-by {
    i {
      cursor: pointer;
      color: #ebebeb;
    }
    i:hover {
      color: #3265f5;
    }
    span {
      padding-left: 8px;
    }
  }
</style>
